package com.example.deepai.service;

import com.example.deepai.model.UIElement;  // 添加这行
import lombok.extern.slf4j.Slf4j;
import org.opencv.core.*;
import org.opencv.imgcodecs.Imgcodecs;
import org.opencv.imgproc.Imgproc;
import org.springframework.stereotype.Service;
import java.util.ArrayList;
import java.util.List;

@Slf4j
@Service
public class OpenCVUIDetectionService {
    static {
        nu.pattern.OpenCV.loadShared();
    }

    public List<UIElement> detectUIElements(String imagePath) {
        List<UIElement> elements = new ArrayList<>();
        Mat image = Imgcodecs.imread(imagePath);
        
        // 边缘检测
        Mat edges = new Mat();
        Imgproc.Canny(image, edges, 50, 150);
        
        // 轮廓检测
        List<MatOfPoint> contours = new ArrayList<>();
        Mat hierarchy = new Mat();
        Imgproc.findContours(edges, contours, hierarchy, 
            Imgproc.RETR_TREE, Imgproc.CHAIN_APPROX_SIMPLE);
        
        // 分析每个轮廓
        for (MatOfPoint contour : contours) {
            Rect rect = Imgproc.boundingRect(contour);
            UIElement element = analyzeUIElement(image, rect);
            if (element != null) {
                elements.add(element);
            }
        }
        
        return elements;
    }
    
    private UIElement analyzeUIElement(Mat image, Rect rect) {
        // 分析区域特征
        Mat roi = new Mat(image, rect);
        
        // 计算颜色直方图
        Mat hist = calculateColorHistogram(roi);
        
        // 基于特征判断UI类型
        String type = classifyUIElement(hist, rect);
        
        if (type != null) {
            return new UIElement(type, rect.x, rect.y, 
                rect.width, rect.height);
        }
        return null;
    }
    
    private Mat calculateColorHistogram(Mat roi) {
        // 计算颜色直方图的具体实现
        List<Mat> bgr = new ArrayList<>();
        Core.split(roi, bgr);
        
        Mat hist = new Mat();
        Imgproc.calcHist(bgr, new MatOfInt(0), 
            new Mat(), hist, new MatOfInt(8), 
            new MatOfFloat(0, 256));
        
        return hist;
    }
    
    private String classifyUIElement(Mat hist, Rect rect) {
        // 基于直方图和形状特征进行分类
        double aspectRatio = (double) rect.width / rect.height;
        
        if (aspectRatio > 3) {
            return "text_field";
        } else if (aspectRatio > 0.8 && aspectRatio < 1.2) {
            return "button";
        }
        
        return null;
    }
}